package com.chenqi.authentication;

import com.chenqi.properties.LoginResponseType;
import com.chenqi.properties.SecurityProperties;
import com.chenqi.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description: 认证失败处理器
 * @program: ardai-securtiy-parent
 * @author: ChenQi
 * @create: 2021-03-2021/3/17-14-57
 */
@Component("customAuthenticationFailureHandler")
//public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        if (LoginResponseType.JSON.equals(securityProperties.getAuthentication().getLoginType())) {
            JsonResult result = JsonResult.build(HttpStatus.UNAUTHORIZED.value(), exception.getMessage());
            String string = result.toJsonString();
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(string);
        }else {
            //失败重定向到页面注意加上 error
            super.setDefaultFailureUrl(securityProperties.getAuthentication().getLoginPage()+"?error");
            super.onAuthenticationFailure(request,response,exception);
        }
    }
}
